package com.example.view.customview;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private ImageView ivOne;
    private ImageView ivTwo;
    private Button btnCreat;
    private Bitmap bm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivOne = findViewById(R.id.iv_anli);
        ivTwo = findViewById(R.id.iv_custom);
        btnCreat = findViewById(R.id.btn_creat);

        bm = ((BitmapDrawable) ivOne.getDrawable()).getBitmap();
        btnCreat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = drawBackground(bm, 25);
                ivTwo.setImageBitmap(bitmap);

            }
        });
    }

    float[] floats = new float[]{150,200,350,200,350,200,350,600,350,600,150,600,150,600,150,200};
    float[] floats2 = new float[]{250,300,450,300,450,300,450,600,450,600,250,600,250,600,250,300};
    private  Bitmap drawBackground(Bitmap bitmap, int pixInterval) {
        /**
         * 注意多个createBiamap重载函数，必须是可变位图对应的重载才能绘制
         * bitmap: 原图像
         * pixInterval: 网格线的横竖间隔，单位:像素
         */
        Bitmap copy = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);  //很重要
        Log.d("kun","width "+bitmap.getWidth()+"height "+bitmap.getHeight());
        Canvas canvas = new Canvas(copy);  //创建画布
        Paint paint = new Paint();  //画笔
        paint.setStrokeWidth(2);  //设置线宽。单位为像素
        paint.setAntiAlias(true); //抗锯齿
        paint.setStyle(Paint.Style.STROKE);//设置风格为空心
        paint.setColor(Color.RED);  //画笔颜色
        canvas.drawBitmap(bitmap,new Matrix(),paint);  //在画布上画一个和bitmap一模一样的图
        canvas.drawLines(floats,paint);
        canvas.drawLines(floats2,paint);
        //根据Bitmap大小，画网格线
        //画横线
//        for (int i = 0; i < bitmap.getHeight() / pixInterval; i++) {
//            canvas.drawLine(0, i * pixInterval, bitmap.getWidth(), i * pixInterval, paint);
//        }
//        //画竖线
//        for (int i = 0; i < bitmap.getWidth() / pixInterval; i++) {
//            canvas.drawLine(i * pixInterval, 0, i * pixInterval, bitmap.getHeight(), paint);
//        }

        return copy;
    }

}
